$: << File.join(File.expand_path(File.dirname(__FILE__)), "..")

require 'rubygems'
require 'optparse'

module OptionParserUtil
	DELM = {'tab'=>"\t",'pipe'=>"|"}
	def OptionParserUtil.handle_delimiter(value, default)
		
		#sanity check
		if (value.nil? or value.empty?) 
			raise Exception, "Invalid delimiter: #{value}" unless default
			return default
		end
		
		value = value.strip.downcase
		return ((DELM.has_key?(value)) ? DELM[value] : value)
	end
	
	def OptionParserUtil.handle_operations(given, valid)
		tmp = []
		given.split(",").each{|v|
			v = v.to_s.strip.downcase
			raise OptionParser::InvalidOption, "Invalid Operation: #{v}. Expecting one of the following: #{valid.join(',')}" unless valid.include?(v)
			tmp << v		
		}
		return tmp
	end
	
	def OptionParserUtil.parse_array(value, type="string")
		raise Exception, "Expecting value" if(value.nil? or value.empty?)
		tokens = value.split(',')
		
		return tokens if type == "string"
		
		tmp = []
		if(type == "int")
			begin
				tokens.each{|v| tmp << Integer(v)}
			rescue ArgumentError => e
					raise OptionParser::ParseError, "Unable to parse #{v} as Integer"
			end
		end
		
		return tmp		
	end
	
	def OptionParserUtil.parse_string_array(value)
		return parse_array(value)
	end
		
	def OptionParserUtil.parse_int_array(value)
		return parse_array(value, "int")
	end
end

